package com.jason.interceptors;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.jason.bean.vo.Menu;

public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		Object loginStatus = request.getSession().getAttribute("LOGIN_STATUS");
		if (loginStatus == null) {
			response.sendRedirect("/user/login");
			return true;
		}
		List<Menu> menus = (List<Menu>) request.getSession().getAttribute("MENUS");
		if (menus!=null) {
			String url = request.getRequestURI();
			url = url.replace(request.getContextPath(), "");
			for (Menu menu : menus) {
				if (checkResource(menu, url)) {
					return true;
				}
			} 
		}
		response.sendError(403, "您无权访问该页面");
		return false;
	}

	private boolean checkResource(Menu menu, String url) {
		boolean flag = false;
		if (menu.getUrl() != null && !menu.getUrl().isEmpty()) {
			flag = menu.getUrl().equals(url);
		}
		if (flag) {
			return true;
		}
		List<Menu> list = menu.getChildMenus();
		if (list != null && !list.isEmpty()) {
			for (Menu menu2 : list) {
				if (checkResource(menu2, url)) {
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
			Object handler, Exception ex) throws Exception {
	}

}
